/**
 * 歌词易(lyricspinyin.net) - 首页JavaScript文件
 */

$(document).ready(function() {
    // 初始化首页搜索功能
    initIndexSearch();
});

/**
 * 初始化首页搜索功能
 */
function initIndexSearch() {
    // 搜索按钮点击
    $('#search-button').click(function() {
        var keyword = $('#search-input').val().trim();
        if (keyword) {
            performIndexSearch(keyword);
        }
    });
    
    // 回车搜索
    $('#search-input').keypress(function(e) {
        if (e.which === 13) {
            var keyword = $(this).val().trim();
            if (keyword) {
                performIndexSearch(keyword);
            }
        }
    });
    
    // 推荐搜索点击
    $('.recommended-search').click(function() {
        var keyword = $(this).data('keyword');
        $('#search-input').val(keyword);
        performIndexSearch(keyword);
    });
    
    // 检查URL参数，自动执行搜索
    var urlParams = new URLSearchParams(window.location.search);
    var keyword = urlParams.get('keyword');
    if (keyword) {
        $('#search-input').val(keyword);
        performIndexSearch(keyword);
    }
}

/**
 * 执行首页搜索
 */
function performIndexSearch(keyword) {
    // 获取语言包配置
    var langs = window.JS_LANGS || {};
    var searchButtons = langs.search_buttons || {};
    
    // 显示加载状态
    $('#search-button').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>' + (searchButtons.searching || '搜索中...'));
    
    // 显示进度条
    showSearchProgress();
    
    $.ajax({
        url: window.current_lang_url + 'api/search',
        type: 'POST',
        data: { keyword: keyword },
        dataType: 'json',
        success: function(response) {
            // 隐藏进度条
            hideSearchProgress();
            
            // 恢复按钮状态
            $('#search-button').prop('disabled', false).html('<i class="fas fa-search mr-2"></i>' + (searchButtons.search || '搜索'));
            
            if (response.code === 200 && response.data) {
                // 检查data是否为空数组
                if (Array.isArray(response.data) && response.data.length === 0) {
                    // 显示没有找到任何结果
                    displayNoResults();
                    return;
                }
                
                // 保存搜索结果到全局变量
                window.currentSearchResult = response.data;
                
                // 判断是否有URL字段
                if (response.data.url && response.data.url.trim() !== '') {
                    // 有URL，直接跳转
                    window.location.href = response.data.url;
                } else {
                    // 没有URL，显示歌词详情
                    displaySearchResult(response.data);
                }
            } else {
                displayNoResults();
            }
        },
        error: function(xhr, status, error) {
            // 隐藏进度条
            hideSearchProgress();
            
            // 恢复按钮状态
            $('#search-button').prop('disabled', false).html('<i class="fas fa-search mr-2"></i>' + (searchButtons.search || '搜索'));
            
            console.error('搜索失败:', error);
            
            // 获取语言包配置
            var langs = window.JS_LANGS || {};
            var messages = langs.messages || {};
            var errorMessage = messages.search_failed || '搜索失败，请稍后重试';
            
            showMessage(errorMessage, 'error');
        }
    });
}

/**
 * 显示搜索进度条
 */
function showSearchProgress() {
    // 移除已存在的进度条
    $('#search-progress').remove();
    
    // 添加自定义CSS样式（如果还没有添加）
    if (!$('#progress-styles').length) {
        $('head').append(`
            <style id="progress-styles">
                @keyframes pulse-slow {
                    0%, 100% { opacity: 0.6; }
                    50% { opacity: 1; }
                }
                .animation-delay-200 {
                    animation-delay: 0.2s;
                }
                .animation-delay-400 {
                    animation-delay: 0.4s;
                }
                .progress-shimmer {
                    background: linear-gradient(90deg, 
                        rgba(255,255,255,0) 0%, 
                        rgba(255,255,255,0.8) 50%, 
                        rgba(255,255,255,0) 100%);
                    background-size: 200% 100%;
                    animation: shimmer 1.5s infinite;
                }
                @keyframes shimmer {
                    0% { background-position: -200% 0; }
                    100% { background-position: 200% 0; }
                }
                .progress-glow {
                    box-shadow: 0 0 10px rgba(139, 92, 246, 0.5);
                }
                .pulse-ring {
                    animation: pulse-ring 2s infinite;
                }
                @keyframes pulse-ring {
                    0% { transform: scale(1); opacity: 1; }
                    50% { transform: scale(1.1); opacity: 0.7; }
                    100% { transform: scale(1); opacity: 1; }
                }
            </style>
        `);
    }
    
    // 获取进度条时间配置（默认15秒）
    var progressTime = window.SEARCH_PROGRESS_TIME || 15;
    
    // 获取语言包配置
    var langs = window.JS_LANGS || {};
    var searchProgress = langs.search_progress || {};
    
    // 创建进度条HTML
    var progressHtml = `
        <div id="search-progress" class="mt-6 w-full max-w-md mx-auto">
            <div class="bg-white rounded-lg shadow-lg p-6 border border-purple-100">
                <div class="text-center mb-4">
                    <div class="flex items-center justify-center mb-2">
                        <div class="w-8 h-8 bg-purple-600 rounded-full flex items-center justify-center mr-2 pulse-ring">
                            <i class="fas fa-search text-white text-sm"></i>
                        </div>
                        <span class="text-gray-700 font-medium">${searchProgress.title || '正在搜索歌词...'}</span>
                    </div>
                </div>
                
                <div class="relative">
                    <div class="w-full bg-gray-300 rounded-full h-4 overflow-hidden shadow-inner border border-gray-400">
                        <div id="progress-bar" class="h-full bg-gradient-to-r from-purple-600 via-blue-600 to-purple-700 rounded-full transition-all duration-300 ease-out progress-shimmer progress-glow shadow-sm" style="width: 0%"></div>
                    </div>
                    <div class="flex justify-between text-xs text-gray-600 mt-2">
                        <span class="font-medium">${searchProgress.searching || '搜索中'}</span>
                        <span id="progress-percentage" class="font-mono font-bold text-purple-600">0${searchProgress.percentage || '%'}</span>
                    </div>
                </div>
                
                <div class="mt-4 text-center">
                    <div class="flex items-center justify-center space-x-2 text-sm text-gray-600">
                        <div class="animate-pulse">
                            <i class="fas fa-circle text-purple-500 text-xs"></i>
                        </div>
                        <span id="progress-text" class="font-medium">${(searchProgress.texts && searchProgress.texts[0]) || '正在分析搜索关键词...'}</span>
                        <div class="animate-pulse animation-delay-200">
                            <i class="fas fa-circle text-blue-500 text-xs"></i>
                        </div>
                        <div class="animate-pulse animation-delay-400">
                            <i class="fas fa-circle text-purple-400 text-xs"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 插入进度条到搜索表单下方
    $('.search-container').after(progressHtml);
    
    // 启动进度条动画
    startProgressAnimation(progressTime);
}

/**
 * 启动进度条动画
 */
function startProgressAnimation(totalTime) {
    var progress = 0;
    var interval = 100; // 更新间隔（毫秒）
    var increment = (100 / (totalTime * 1000)) * interval; // 每次增长的百分比
    
    // 获取语言包配置
    var langs = window.JS_LANGS || {};
    var searchProgress = langs.search_progress || {};
    
    // 进度文本数组 - 从语言包获取
    var progressTexts = searchProgress.texts || [
        '🔍 正在分析搜索关键词...',
        '🎵 正在连接歌词数据库...',
        '🎶 正在匹配相关歌曲...',
        '📝 正在获取歌词内容...',
        '✨ 正在优化搜索结果...',
        '🎼 正在准备展示内容...',
        '🎉 即将完成搜索...'
    ];
    
    var textIndex = 0;
    var textChangeInterval = totalTime * 1000 / progressTexts.length;
    var nextTextChange = textChangeInterval;
    
    window.progressTimer = setInterval(function() {
        progress += increment;
        
        if (progress >= 100) {
            progress = 100;
        }
        
        // 更新进度条
        $('#progress-bar').css('width', progress + '%');
        $('#progress-percentage').text(Math.round(progress) + (searchProgress.percentage || '%'));
        
        // 添加进度条颜色变化效果
        if (progress >= 80) {
            $('#progress-bar').removeClass('from-purple-600 via-blue-600 to-purple-700')
                             .addClass('from-green-500 via-emerald-500 to-green-600');
        } else if (progress >= 50) {
            $('#progress-bar').removeClass('from-purple-600 via-blue-600 to-purple-700')
                             .addClass('from-blue-500 via-indigo-500 to-blue-600');
        }
        
        // 更新进度文本
        if (Date.now() - window.progressStartTime > nextTextChange && textIndex < progressTexts.length - 1) {
            textIndex++;
            $('#progress-text').fadeOut(200, function() {
                $(this).text(progressTexts[textIndex]).fadeIn(200);
            });
            nextTextChange += textChangeInterval;
        }
        
        // 如果进度达到100%，停止计时器
        if (progress >= 100) {
            clearInterval(window.progressTimer);
            $('#progress-text').fadeOut(200, function() {
                $(this).text(searchProgress.complete || '🎉 搜索完成！').fadeIn(200);
            });
        }
    }, interval);
    
    // 记录开始时间
    window.progressStartTime = Date.now();
}

/**
 * 隐藏搜索进度条
 */
function hideSearchProgress() {
    // 清除计时器
    if (window.progressTimer) {
        clearInterval(window.progressTimer);
        window.progressTimer = null;
    }
    
    // 获取语言包配置
    var langs = window.JS_LANGS || {};
    var searchProgress = langs.search_progress || {};
    
    // 如果进度条存在，先完成动画再隐藏
    if ($('#search-progress').length > 0) {
        $('#progress-bar').css('width', '100%')
                         .removeClass('from-purple-600 via-blue-600 to-purple-700')
                         .removeClass('from-blue-500 via-indigo-500 to-blue-600')
                         .addClass('from-green-500 via-emerald-500 to-green-600');
        $('#progress-percentage').text('100' + (searchProgress.percentage || '%'));
        $('#progress-text').text(searchProgress.complete || '🎉 搜索完成！');
        
        // 延迟隐藏，让用户看到完成状态
        setTimeout(function() {
            $('#search-progress').fadeOut(500, function() {
                $(this).remove();
                // 清理添加的样式
                $('#progress-styles').remove();
            });
        }, 800);
    }
}

/**
 * 显示消息提示（如果main.js的showMessage不可用）
 */
function showMessage(message, type) {
    // 如果全局showMessage函数存在，使用它
    if (typeof window.showMessage === 'function') {
        window.showMessage(message, type);
        return;
    }
    
    // 否则使用简单的alert
    alert(message);
}

/**
 * 显示搜索结果
 */
function displaySearchResult(lyric) {
    $('#search-results').removeClass('hidden');
    $('#results-container').empty();
    $('#no-results').addClass('hidden');
    
    // 直接显示歌词详情，使用全宽布局
    $('#results-container').removeClass('grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6');
    var html = createLyricDetail(lyric);
    $('#results-container').append(html);
    
    // 添加动画效果
    $('.lyric-detail').addClass('fade-in');
    
    // 滚动到搜索结果（延迟执行，确保动画开始后再滚动）
    setTimeout(function() {
        $('html, body').animate({
            scrollTop: $('#search-results').offset().top - 100
        }, 500);
    }, 200);
    
    // 绑定重新搜索按钮事件
    $(document).off('click', '.new-search').on('click', '.new-search', function() {
        // 清空搜索结果，回到搜索页面
        $('#search-results').addClass('hidden');
        $('#search-input').focus();
        
        // 滚动到搜索框
        $('html, body').animate({
            scrollTop: $('#search-input').offset().top - 100
        }, 500);
    });
}

/**
 * 创建歌词详情HTML（类似详情页）
 */
function createLyricDetail(lyric) {
    // 获取语言包配置
    var langs = window.JS_LANGS || {};
    var lyricDetail = langs.lyric_detail || {};
    
    // 处理歌词内容
    var lyricsContent = '';
    if (lyric.lyrics && Array.isArray(lyric.lyrics) && lyric.lyrics.length > 0) {
        // 新的数据结构：中文和拼音对照
        lyricsContent = lyric.lyrics.map(function(line) {
            return `
                <div class="lyrics-line hover:bg-blue-50 transition-colors py-2 mb-3">
                    <div class="original-text text-sm font-medium text-gray-600 leading-tight">
                        ${line.original || ''}
                    </div>
                    <div class="pinyin-text text-xl text-blue-600 font-mono leading-tight tracking-wide">
                        ${line.pinyin || ''}
                    </div>
                </div>
            `;
        }).join('');
    } else if (typeof lyric.lyrics === 'string') {
        // 兼容旧的字符串格式
        lyricsContent = `<div class="text-center whitespace-pre-line">${lyric.lyrics}</div>`;
    } else {
        // 无歌词内容
        lyricsContent = `
            <div class="text-center py-12">
                <i class="fas fa-music text-4xl text-gray-300 mb-4"></i>
                <p class="text-gray-500 text-lg">${lyricDetail.no_lyrics || '暂无歌词内容'}</p>
            </div>
        `;
    }
    
    return `
        <div class="lyric-detail opacity-0 w-full">
            <div class="container mx-auto px-0 md:px-4 max-w-6xl">
                <div class="bg-white md:rounded-2xl shadow-2xl overflow-hidden mx-auto" style="min-height: 80vh;">
                    <!-- 歌曲信息头部 -->
                    <div class="bg-gradient-to-r from-cyan-500 to-blue-600 text-white py-6 md:py-8 px-4 md:px-8">
                        <div class="max-w-4xl mx-auto text-center">
                            <!-- 歌曲标题和歌手 -->
                            <div class="flex items-center justify-center mb-4">
                                <div class="w-12 h-12 md:w-16 md:h-16 bg-white bg-opacity-20 rounded-full flex items-center justify-center mr-3 md:mr-4">
                                    <i class="fas fa-music text-xl md:text-2xl"></i>
                                </div>
                                <div class="text-left">
                                    <h1 class="text-2xl md:text-3xl lg:text-4xl font-bold">${lyric.title || '未知歌曲'}</h1>
                                    ${lyric.artist ? `<p class="text-cyan-100 text-base md:text-lg mt-1"><i class="fas fa-microphone mr-2"></i>${lyric.artist}</p>` : ''}
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 歌词内容 -->
                    <div class="py-4 md:py-8 px-4 md:px-8">
                        <div class="max-w-5xl mx-auto">
                            <!-- 顶部操作按钮容器 -->
                            <div class="flex flex-col md:flex-row justify-between items-center mb-4 md:mb-6 gap-3 md:gap-4">
                                <div class="flex items-center">
                                    <h2 class="text-xl md:text-2xl font-bold text-gray-800 mr-3 md:mr-4">
                                        <i class="fas fa-language text-cyan-500 mr-2"></i>
                                        ${lyricDetail.lyrics_content || '歌词拼音对照'}
                                    </h2>
                                </div>
                                <div class="flex items-center space-x-2 md:space-x-3">
                                    <!-- 语言切换按钮 -->
                                    <button class="language-toggle-btn flex items-center space-x-1 md:space-x-2 bg-purple-500 hover:bg-purple-600 text-white transition-colors px-3 md:px-4 py-2 rounded-lg shadow-md hover:shadow-lg text-sm font-medium w-full md:w-auto justify-center" data-mode="both">
                                        <i class="fas fa-language"></i>
                                        <span class="toggle-text">${lyricDetail.lang_toggle_both || '双语'}</span>
                                    </button>
                                    <button class="download-btn flex items-center space-x-1 md:space-x-2 bg-cyan-500 hover:bg-cyan-600 text-white transition-colors px-3 md:px-4 py-2 rounded-lg shadow-md hover:shadow-lg text-sm font-medium w-full md:w-auto justify-center">
                                        <i class="fas fa-download"></i>
                                        <span class="font-medium">${lyricDetail.download || '下载'}</span>
                                    </button>
                                    <button class="print-btn flex items-center space-x-1 md:space-x-2 bg-blue-500 hover:bg-blue-600 text-white transition-colors px-3 md:px-4 py-2 rounded-lg shadow-md hover:shadow-lg text-sm font-medium w-full md:w-auto justify-center">
                                        <i class="fas fa-print"></i>
                                        <span class="font-medium">${lyricDetail.print || '打印'}</span>
                                    </button>
                                </div>
                            </div>
                            
                            <!-- 歌词显示区域 -->
                            <div class="lyrics-content bg-gradient-to-br from-gray-50 to-blue-50 rounded-xl md:rounded-2xl p-4 md:p-6 shadow-inner border border-gray-200" style="min-height: 400px;">
                                ${lyricsContent}
                            </div>
                        </div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="py-6 md:py-8 px-4 md:px-8 bg-gradient-to-r from-gray-50 to-cyan-50 border-t border-gray-200">
                        <div class="max-w-4xl mx-auto">
                            <div class="flex flex-col md:flex-row justify-center items-center space-y-3 md:space-y-0 md:space-x-6">
                                <!-- 语言切换按钮 -->
                                <button class="language-toggle-btn flex items-center space-x-1 md:space-x-2 bg-purple-500 hover:bg-purple-600 text-white transition-colors px-3 md:px-4 py-2 rounded-lg shadow-md hover:shadow-lg text-sm font-medium w-full md:w-auto justify-center" data-mode="both">
                                    <i class="fas fa-language"></i>
                                    <span class="toggle-text">${lyricDetail.lang_toggle_both || '双语'}</span>
                                </button>
                                <button class="download-btn flex items-center space-x-1 md:space-x-2 bg-cyan-500 hover:bg-cyan-600 text-white transition-colors px-3 md:px-4 py-2 rounded-lg shadow-md hover:shadow-lg text-sm font-medium w-full md:w-auto justify-center">
                                    <i class="fas fa-download"></i>
                                    <span class="font-medium">${lyricDetail.download || '下载'}</span>
                                </button>
                                <button class="print-btn flex items-center space-x-1 md:space-x-2 bg-blue-500 hover:bg-blue-600 text-white transition-colors px-3 md:px-4 py-2 rounded-lg shadow-md hover:shadow-lg text-sm font-medium w-full md:w-auto justify-center">
                                    <i class="fas fa-print"></i>
                                    <span class="font-medium">${lyricDetail.print || '打印'}</span>
                                </button>
                                <button class="new-search bg-gradient-to-r from-cyan-500 to-blue-600 hover:from-cyan-600 hover:to-blue-700 text-white px-6 md:px-8 py-2 md:py-3 rounded-xl transition-colors font-medium shadow-lg hover:shadow-xl w-full md:w-auto text-sm md:text-base">
                                    <i class="fas fa-search mr-2"></i>${lyricDetail.new_search || '重新搜索'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

/**
 * 显示无结果
 */
function displayNoResults() {
    $('#search-results').removeClass('hidden');
    $('#results-container').html(createNoResultsHTML());
    $('#no-results').addClass('hidden'); // 隐藏原有的无结果元素，使用新的HTML结构
}

/**
 * 创建无结果显示HTML
 */
function createNoResultsHTML() {
    // 获取语言包配置
    var langs = window.JS_LANGS || {};
    var noResults = langs.no_results || {};
    
    return `
        <div class="no-results-container w-full max-w-2xl mx-auto text-center py-12">
            <div class="bg-white rounded-2xl shadow-lg p-8 border border-gray-100">
                <div class="mb-6">
                    <i class="fas fa-search text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-2xl font-bold text-gray-700 mb-2">${noResults.title || '未找到相关歌词'}</h3>
                    <p class="text-gray-500">${noResults.subtitle || '很抱歉，没有找到您搜索的歌词内容'}</p>
                </div>
                
                <div class="bg-blue-50 rounded-lg p-6 mb-6">
                    <h4 class="font-semibold text-blue-800 mb-3">${noResults.suggestions_title || '搜索建议：'}</h4>
                    <ul class="text-left text-blue-700 space-y-2">
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-blue-500 mr-2 mt-1"></i>
                            <span>${noResults.suggestion_1 || '检查歌曲名或歌手名的拼写是否正确'}</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-blue-500 mr-2 mt-1"></i>
                            <span>${noResults.suggestion_2 || '尝试使用歌曲的完整名称或常见别名'}</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-blue-500 mr-2 mt-1"></i>
                            <span>${noResults.suggestion_3 || '可以只输入歌手名查看该歌手的所有歌曲'}</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-blue-500 mr-2 mt-1"></i>
                            <span>${noResults.suggestion_4 || '使用歌词中的关键词进行搜索'}</span>
                        </li>
                    </ul>
                </div>
                
                <div class="space-y-4">
                    <button class="new-search bg-purple-600 hover:bg-purple-700 text-white px-8 py-3 rounded-lg transition-colors font-medium shadow-lg hover:shadow-xl w-full">
                        <i class="fas fa-search mr-2"></i>${noResults.try_again || '重新搜索'}
                    </button>
                    
                    <div class="flex space-x-3">
                        <button class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 px-6 py-2 rounded-lg transition-colors">
                            <i class="fas fa-random mr-2"></i>${noResults.random_song || '随机歌曲'}
                        </button>
                        <button class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 px-6 py-2 rounded-lg transition-colors">
                            <i class="fas fa-fire mr-2"></i>${noResults.hot_songs || '热门歌曲'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
}

/**
 * 获取当前语言
 */
function getCurrentLanguage() {
    // 从cookie或其他地方获取当前语言，默认为zh-cn
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();
        if (cookie.indexOf('think_lang=') === 0) {
            return cookie.substring('think_lang='.length);
        }
    }
    return 'zh-cn';
} 